package com.zhuziym.ketfile;

import com.zhuziym.utils.Const;
import org.apache.commons.lang3.RandomStringUtils;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.util.EnvUtil;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryResult;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepStatus;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

public class DemoClassReouse {
    public static void main1(String[] args) throws IOException, URISyntaxException {
        if (args.length < 2) {
            return;
        }

        initKettleHome("conf");
        String path = args[1];
        switch (args[0]) {
            case "job":
                runJob(null, path);
                break;
            default:
                runTransfer(null, path);
                break;
        }

    }

    public static void main(String[] args) {
        String jobPath = System.getProperty("user.dir") + "/kettleFile/job_mkdir.kjb";
        initKettleHome("conf");
        runJob(null, jobPath);
        String tranPath = System.getProperty("user.dir") + "/kettleFile/readFrommysql.ktr";
        // runTransfer(null, tranPath);
    }


    /**
     * kettle_home是在 设定目录下面的.kettle文件夹
     */
    public static void initKettleHome(String confFile) {
        String ketPropFile = KettleFile.class.getClassLoader().getResource(confFile).getFile();

        // TODO JNDIhome
        System.getProperties().put("KETTLE_JNDI_ROOT", ketPropFile + "/simple-jndi");
        //		System.setProperty("java.naming.factory.initial", "org.osjava.sj.SimpleContextFactory");
        //		System.setProperty("org.osjava.sj.root", ketPropFile + "/simple-jndi");
        //		System.setProperty("org.osjava.sj.delimiter", "/");
        System.getProperties().put(Const.KETTLE_HOME, ketPropFile);
    }

    /**
     * 运行转换文件方法
     *
     * @param params  多个参数变量值
     * @param ktrPath 转换文件的路径，后缀ktr
     */
    public static void runTransfer(String[] params, String ktrPath) {
        Trans trans = null;
        try {
            // 转换元对象
            KettleEnvironment.init(true);// 初始化
            EnvUtil.environmentInit();
            TransMeta transMeta = new TransMeta(ktrPath);
            trans = new Trans(transMeta);
            // 执行转换 日志放在这里合适，
            trans.setLogLevel(LogLevel.BASIC);
            //sh kitchen.sh -rep=initech_pdi_repo -user=pgibbons -pass=lumburghsux -job=TPS_reports_2011
            trans.execute(null);
            // 等待转换执行结束
            trans.waitUntilFinished();
            // 执行结果
            boolean result = trans.getResult().getResult();

            // kettle 界面执行面板的 步骤度量
            System.out.println("kettle 界面执行面板的 步骤度量");
            for (int i = 0; i < trans.nrSteps(); i++) {
                StepInterface baseStep = trans.getRunThread(i);
                StepStatus stepStatus = new StepStatus(baseStep);
                System.out.println("stepname=" + stepStatus.getStepname() + ",errors=" + stepStatus.getErrors() + ",statusDescription=" + stepStatus.getStatusDescription());
            }
            // 抛出异常
            if (trans.getErrors() > 0) {
                throw new Exception("There are errors during transformation exception!(传输过程中发生异常)");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String runJob(String[] params, String jobPath) {
        try {
            KettleEnvironment.init(true);
            EnvUtil.environmentInit();
            // jobname 是Job脚本的路径及名称
            JobMeta jobMeta = new JobMeta(jobPath, null);
            //TODO 设置参数 覆盖了 文件中的默认值
            jobMeta.setParameterValue("title", "jobMeta-" + RandomStringUtils.randomAlphanumeric(5));

            //没有覆盖 文件中设置的变量
            jobMeta.setVariable("HOSTNAME", "jobMeta-HOSTNAME" + RandomStringUtils.randomNumeric(5));
            Job job = new Job(null, jobMeta);
            //设置没生效
            job.setArguments(new String[]{"logfile=C:/Users/Administrator/Desktop/ke/kettleDemo/kettleFile/log/我自定义.log"});
            job.setLogLevel(LogLevel.BASIC);
            //TODO 参数 |sh kitchen.sh -rep=initech_pdi_repo -user=pgibbons -pass=lumburghsux -job=TPS_reports_2011
            //https://help.pentaho.com/Documentation/7.1/0L0/0Y0/070
            job.start();
            job.waitUntilFinished();
            job.setFinished(true);

            if (job.isFinished()) {
                List<JobEntryResult> jobEntryResults = job.getJobEntryResults();
                for (JobEntryResult jobEntryResult : jobEntryResults) {
                    System.out.println("执行步骤=" + jobEntryResult.getJobEntryName() + ",执行状态=" + jobEntryResult.getResult().getResult());
                    final String logText = jobEntryResult.getResult().getLogText();
                }

            }
            // 执行 打印的日志 等全在这个xml中
            System.out.println("----------------------------------------------------");
            final String logText = job.getResult().getLogText();
            System.out.println(logText);
            if (job.getErrors() > 0) {
                System.out.println("transformation error");
            } else {
                System.out.println("transformation successfully");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
